 package ProjectorTest;

import java.awt.*;
import javax.swing.*;
import mote.*;

public class ProjectorTest {
	public static void main(String[] args)
	{
		new ProjectorTest();
	}
	
	int top, bottom;
	
	public ProjectorTest()
	{
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(800,600);
		ProjTest pt = new ProjTest();
		frame.add(pt);
		frame.setVisible(true);
		
		MoteCollection mc = new MoteCollection();
		MoteBridge mb = new MoteBridge(mc);
		try {
			Thread.sleep(2000);
			Mote m = mc.Motes().get(0);
			
			System.out.println("Place the mote at the top and press any key to continue");
			System.in.read();
			top = (int) m.AverageReading(20);
			
			System.out.println("Top set at: " + top);
			System.out.println("Place the mote at the bottom and press any key to continue");
			System.in.read();
			
			bottom = (int) m.AverageReading(20);
			System.out.println("Bottom set at: " + bottom);
			
			while(true)
			{
				Thread.sleep(100);
				int pos = calculatePosition(m.AverageReading(10));
				System.out.println("LightReading: " + m.Reading() + " position: " + pos);
				pt.setPosition(pos);
				frame.repaint();
			}
			
		}
		//TODO fix this, this is such a bad idea
		catch (Exception e) {}
		

	}
	
	private int calculatePosition(double reading) {
		double val = ((1.0 - (((double)(reading-bottom))/((double)(top-bottom))))*600.0);
		if(val<0)
			val = 0;
		else if(val>600)
			val = 600;
		
		return (int) val;
	}

	class ProjTest extends JComponent
	{
		final int LIGHT_GRAY_POINT = 400;
		int pos = 0;
		public void paint(Graphics g)
		{
			Graphics2D g2d = (Graphics2D)g;
			
			GradientPaint grad1 = new GradientPaint(0, -200, Color.white, 0, LIGHT_GRAY_POINT, Color.lightGray);
			GradientPaint grad2 = new GradientPaint(0, LIGHT_GRAY_POINT, Color.lightGray, 0, getHeight() - 1, Color.gray);
			g2d.setPaint(grad1);
			g2d.fillRect(0, 0, 200, LIGHT_GRAY_POINT);
			g2d.setPaint(grad2);
			g2d.fillRect(0, LIGHT_GRAY_POINT, 200, getHeight() - 1);
			
			g2d.setPaint(Color.black);
			g2d.drawLine(200, pos, 250, pos);
		}
		
		public void setPosition(int pos)
		{
			this.pos=pos;
		}
	}
}
